package com.kt.sso.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import javax.servlet.Servlet;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Desc:
 *
 * @author: keen
 * Date: 2019-09-22
 * Time: 16:20
 */
@Configuration
public class DruidConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        return dataSource;
    }

    /**
     * 1、配置Druid的后台管理
     */
    @Bean
    public ServletRegistrationBean statViewServlet() {
        StatViewServlet statViewServlet = new StatViewServlet();
        ServletRegistrationBean<Servlet> servletRegistrationBean =
                new ServletRegistrationBean<>(statViewServlet, "/druid/*");
        /**
         * 设置初始化参数
         * public static final String SESSION_USER_KEY = "druid-user";
         * 后台登录用户名
         *     public static final String PARAM_NAME_USERNAME = "loginUsername";
         *     登录密码
         *     public static final String PARAM_NAME_PASSWORD = "loginPassword";
         *     允许登录IP，默认所有
         *     public static final String PARAM_NAME_ALLOW = "allow";
         *     禁止登录IP
         *     public static final String PARAM_NAME_DENY = "deny";
         */
        HashMap<String, String> initParameters = new HashMap<>(2);
        initParameters.put("loginUsername", "admin");
        initParameters.put("loginPassword", "admin");
        servletRegistrationBean.setInitParameters(initParameters);
        return servletRegistrationBean;
    }

    /**
     * 2、配置监控的filter
     */

    @Bean
    public FilterRegistrationBean statViewFilter() {
        WebStatFilter webStatFilter = new WebStatFilter();
        FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<>(webStatFilter);
        HashMap<String, String> initParameters = new HashMap<>(2);
        initParameters.put("exclusions", "*js,*.css,/druid/*");
        filterRegistrationBean.setInitParameters(initParameters);
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/**"));
        return filterRegistrationBean;
    }
}
